﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;

using Bricks.Component.Utils;
using Bricks.Business.Models.ProphaseManagement;
using Bricks.Business.Models.ProjectContract;
using Bricks.Site.Models;
using Bricks.Business.Data.Repositories.ProphaseManagement;
using Bricks.Business.Data.Repositories.ProjectContract;
using Bricks.Business.Service;
using Bricks.Business.Data.Repositories.Document;
using Bricks.Business.Models.Document;
using Bricks.Business.Data.Repositories.Account;
using Bricks.Component.Utils.Extensions;

namespace ChiDao.Business.Service.Impl
{
    [Export(typeof(IProphaseFileInfoService))]
    internal class ProphaseFileInfoService : IProphaseFileInfoService
    {
        [Import]
        protected IProjectStageInfoRepository ProjectStageInfoRepository { get; set; }
        [Import]
        protected IProphaseFileInfoRepository ProphaseFileInfoRepository { get; set; }
        [Import]
        protected IOrgInfoRepository OrgInfoRepository { get; set; }
        [Import]
        protected IUserInfoRepository UserInfoRepository { get; set; }
        [Import]
        protected IDocumentInfoRepository DocumentInfoRepository { get; set; }


        public List<ProphaseFileInfoView> GetProphaseFileInfoList(Guid projectID, Guid userID)
        {
            List<ProphaseFileInfoView> lstProphaseFileInfoView = new List<ProphaseFileInfoView>();
            var prophaseFileInfos = from ps in ProjectStageInfoRepository.Entities
                                    join pf in ProphaseFileInfoRepository.Entities on ps.ID equals pf.ProjectStageID into JoinedEmpProphaseFile
                                    from empPf in JoinedEmpProphaseFile.DefaultIfEmpty()
                                    where ps.PID == projectID
                                    orderby ps.OrderNo, empPf.OrderNo
                                    select new
                                    {
                                        ID = empPf.ID == null ? Guid.Empty : empPf.ID,
                                        ProjectStageID = ps.ID,
                                        ps.StageName,
                                        ProjectStageDealPerson = ps.DealPerson,
                                        empPf.FileName,
                                        empPf.PreparationStatus,
                                        empPf.PlannedCompletionTime,
                                        empPf.ApprovalNumber,
                                        empPf.ApprovalTime,
                                        empPf.DealPersonOrg,
                                        empPf.DealPerson
                                    };
            foreach (var prophaseFileInfo in prophaseFileInfos)
            {
                ProphaseFileInfoView prophaseFileInfoView = new ProphaseFileInfoView();
                prophaseFileInfoView.ID = prophaseFileInfo.ID;
                prophaseFileInfoView.ProjectStageID = prophaseFileInfo.ProjectStageID;
                prophaseFileInfoView.ProjectStageDealPerson = prophaseFileInfo.ProjectStageDealPerson;
                prophaseFileInfoView.ProjectStageName = prophaseFileInfo.StageName;
                prophaseFileInfoView.FileName = prophaseFileInfo.FileName;
                prophaseFileInfoView.PreparationStatus = prophaseFileInfo.PreparationStatus;
                prophaseFileInfoView.PlannedCompletionTime = prophaseFileInfo.PlannedCompletionTime;
                prophaseFileInfoView.ApprovalNumber = prophaseFileInfo.ApprovalNumber;
                prophaseFileInfoView.ApprovalTime = prophaseFileInfo.ApprovalTime;
                prophaseFileInfoView.DealPersonOrg = prophaseFileInfo.DealPersonOrg;
                prophaseFileInfoView.DealPersonOrgName = GetOrgInfoByID(prophaseFileInfo.DealPersonOrg);
                prophaseFileInfoView.DealPerson = prophaseFileInfo.DealPerson;
                prophaseFileInfoView.DealPersonName = GetUserInfoByID(prophaseFileInfo.DealPerson);
                prophaseFileInfoView.Attachment = GetAttachment(prophaseFileInfo.ID);
                prophaseFileInfoView.LoginUserID = userID;
                lstProphaseFileInfoView.Add(prophaseFileInfoView);
            }
            return lstProphaseFileInfoView;
        }

        private string GetStageName(Guid projectStageID)
        {
            string stageName = string.Empty;
            ProjectStageInfo projectStageInfo = ProjectStageInfoRepository.Entities.FirstOrDefault(p => p.ID == projectStageID);
            if (projectStageInfo != null)
            {
                stageName = projectStageInfo.StageName;
            }
            return stageName;
        }

        public string GetOrgInfoByID(string id)
        {
            string result = string.Empty;
            if (!string.IsNullOrEmpty(id))
            {
                Guid orgID = id.ToGuid();
                var org = OrgInfoRepository.Entities.FirstOrDefault(m => m.ID == orgID);
                if (org != null)
                {
                    result = org.OrgName;
                }
            }
            return result;
        }

        public string GetUserInfoByID(string id)
        {
            string result = string.Empty;
            if (!string.IsNullOrEmpty(id))
            {
                Guid userID = id.ToGuid();
                var user = UserInfoRepository.Entities.FirstOrDefault(m => m.ID == userID);
                if (user != null)
                {
                    result = user.UserName;
                }
            }
            return result;
        }

        private string GetAttachment(Guid instanceID)
        {
            string attachment = string.Empty;
            List<DocumentInfo> documents = DocumentInfoRepository.Entities.Where(d => d.InstanceID == instanceID && d.Tag == "ProphaseManagement/ProphaseFileList/Attachment").ToList();
            for (int i = 0; i < documents.Count(); i++)
            {
                if (i == documents.Count() - 1)
                {
                    attachment += "<a target=\"_blank\" href='" + documents[i].FilePath + "'>" + documents[i].FileName + "</a> ";
                }
                else
                {
                    attachment += "<a target=\"_blank\" href='" + documents[i].FilePath + "'>" + documents[i].FileName + "</a>、 ";
                }
            }
            //foreach (DocumentInfo documentInfo in documents)
            //{
            //    attachment += documentInfo.FileName + "  ";                
            //}
            return attachment;
        }



        public ProphaseFileInfoView GetProphaseFileInfo(Guid id)
        {
            ProphaseFileInfoView prophaseFileInfoView = null;
            ProphaseFileInfo prophaseFileInfo = ProphaseFileInfoRepository.Entities.FirstOrDefault(p => p.ID == id);
            if (prophaseFileInfo != null)
            {
                prophaseFileInfoView = new ProphaseFileInfoView()
                {
                    ID = prophaseFileInfo.ID,
                    ProjectID = prophaseFileInfo.ProjectID,
                    ProjectStageID = prophaseFileInfo.ProjectStageID,
                    ProjectStageName = GetStageName(prophaseFileInfo.ProjectStageID),
                    FileName = prophaseFileInfo.FileName,
                    PreparationStatus = prophaseFileInfo.PreparationStatus,
                    PlannedCompletionTime = prophaseFileInfo.PlannedCompletionTime,
                    ApprovalNumber = prophaseFileInfo.ApprovalNumber,
                    ApprovalTime = prophaseFileInfo.ApprovalTime,
                    DealPersonOrg = prophaseFileInfo.DealPersonOrg,
                    DealPersonOrgName = GetOrgInfoByID(prophaseFileInfo.DealPersonOrg),
                    DealPerson = prophaseFileInfo.DealPerson,
                    DealPersonName = GetUserInfoByID(prophaseFileInfo.DealPerson),
                    DealTime = prophaseFileInfo.DealTime,
                    Content = prophaseFileInfo.Content,
                    Attachment = prophaseFileInfo.Attachment
                };
            }
            return prophaseFileInfoView;
        }

        public void SaveProphaseFileInfo(ProphaseFileInfoView prophaseFileInfoView)
        {
            ProphaseFileInfo prophaseFileInfo = ProphaseFileInfoRepository.Entities.FirstOrDefault(p => p.ID == prophaseFileInfoView.ID);
            if (prophaseFileInfo == null)
            {
                Add(prophaseFileInfoView);
            }
            else
            {
                Modify(prophaseFileInfo, prophaseFileInfoView);
            }
        }

        private void Add(ProphaseFileInfoView prophaseFileInfoView)
        {
            ProphaseFileInfo record = new ProphaseFileInfo();
            record.ID = prophaseFileInfoView.ID;
            record.ProjectID = prophaseFileInfoView.ProjectID;
            record.ProjectStageID = prophaseFileInfoView.ProjectStageID;
            record.FileName = prophaseFileInfoView.FileName;
            record.PreparationStatus = prophaseFileInfoView.PreparationStatus;
            record.PlannedCompletionTime = prophaseFileInfoView.PlannedCompletionTime;
            record.ApprovalNumber = prophaseFileInfoView.ApprovalNumber;
            record.ApprovalTime = prophaseFileInfoView.ApprovalTime;
            record.DealPersonOrg = prophaseFileInfoView.DealPersonOrg;
            record.DealPerson = prophaseFileInfoView.DealPerson;
            record.DealTime = prophaseFileInfoView.DealTime;
            record.Content = prophaseFileInfoView.Content;
            record.Attachment = prophaseFileInfoView.Attachment;
            record.OrderNo = GetOrderNo(prophaseFileInfoView);
            ProphaseFileInfoRepository.Insert(record);
        }

        private void Modify(ProphaseFileInfo record, ProphaseFileInfoView prophaseFileInfoView)
        {
            if (record.ProjectStageID != prophaseFileInfoView.ProjectStageID)
            {
                record.OrderNo = GetOrderNo(prophaseFileInfoView);
            }
            record.ProjectStageID = prophaseFileInfoView.ProjectStageID;
            record.FileName = prophaseFileInfoView.FileName;
            record.PreparationStatus = prophaseFileInfoView.PreparationStatus;
            record.PlannedCompletionTime = prophaseFileInfoView.PlannedCompletionTime;
            record.ApprovalNumber = prophaseFileInfoView.ApprovalNumber;
            record.ApprovalTime = prophaseFileInfoView.ApprovalTime;
            record.DealPersonOrg = prophaseFileInfoView.DealPersonOrg;
            record.DealTime = prophaseFileInfoView.DealTime;
            record.Content = prophaseFileInfoView.Content;
            record.Attachment = prophaseFileInfoView.Attachment;
            ProphaseFileInfoRepository.Update(record);
        }

        private int GetOrderNo(ProphaseFileInfoView prophaseFileInfoView)
        {
            int orderNo = 1;
            IQueryable<ProphaseFileInfo> lstProphaseFileInfo = ProphaseFileInfoRepository.Entities.Where(p => p.ProjectStageID == prophaseFileInfoView.ProjectStageID);
            if (lstProphaseFileInfo != null && lstProphaseFileInfo.Count() > 0)
            {
                object max = lstProphaseFileInfo.Max(p => p.OrderNo);
                orderNo = Convert.ToInt32(max) + 1;
            }
            return orderNo;
        }



        public OperationResult Delete(Guid id)
        {
            PublicHelper.CheckArgument(id, "id");
            ProphaseFileInfo record = ProphaseFileInfoRepository.Entities.FirstOrDefault(s => s.ID == id);
            if (record == null)
                return new OperationResult(OperationResultType.QueryNull, "未找到指定的记录");

            if (ProphaseFileInfoRepository.Delete(record) >= 0)
            {
                string sql = @"DELETE FROM ProphaseFileModifyInfoes WHERE PID='" + id + "';";
                ProphaseFileInfoRepository.ExeSqlCommon(sql);
                return new OperationResult(OperationResultType.Success, "删除成功", record);
            }
            return new OperationResult(OperationResultType.Error, "删除失败");
        }


        public OperationResult SetOrder(Guid id, Guid projectStageID, string upOrDown)
        {
            IQueryable<ProphaseFileInfo> lstProphaseFileInfo = ProphaseFileInfoRepository.Entities.Where(p => p.ProjectStageID == projectStageID);
            var exeResult = ProphaseFileInfoRepository.SetOrder(lstProphaseFileInfo, id, "OrderNo", upOrDown);  //执行向上向下操作
            return exeResult;
        }
    }
}